package com.artifex.ebook;

import android.util.Log;
import java.io.File;
import android.widget.Toast;

public class mp3decoder {
    static {  
        System.loadLibrary("mad");  
        Log.d("mp3decoder", "load library sucessful");
    } 
	private int ret;  
    private long m_RealOffset;
    private long m_FileSwapOffset;
    private String filepath;
    private int m_Pdfsize;
    private int m_currentfilesize;
    public mp3decoder(int pdfoffset) {  
    	
    	m_RealOffset = m_FileSwapOffset = 0;
    	filepath = "";
    	m_Pdfsize = pdfoffset;
    	m_currentfilesize = 0;
    }  
  
    private native int initAudioPlayer(String file,long StartAddr,long len);  
  
    public native int getAudioBuf(short[] audioBuffer, int numSamples);  
  
    public native void closeAduioFile();  
  
    public native int getAudioSamplerate();  
    
    private native int seekPlayPos(long seekpos,long len);
    
    public int SeekPlayPos(long seekpos ,long len)
    {
    	if(m_FileSwapOffset == 0 || filepath == "" || m_Pdfsize == 0)
    		return -1;
    	//seekpos += EbookConstants.ENCRYKEYMAX;
    	if(seekpos + len > m_FileSwapOffset)
    	{
    		if(!filepath.toLowerCase().endsWith(EbookConstants.EBOOKTXE))
        	{
    			String refile = filepath.substring(0, filepath.lastIndexOf('.') + 1);
            	refile += EbookConstants.EBOOKTXE;
            	File file = new File(refile);
            	if(file.exists())
            	{
            		if(InitPlayFile(refile,0,0) == -1)
            			return -1; 
            	}
            	else
            	{
            		return -1;
            	}
            	m_RealOffset = seekpos - EbookConstants.ENCRYKEYMAX;;
        	}
        	return seekPlayPos(seekpos - m_RealOffset,len);
    	}
    	else
    	{
    		if(!filepath.toLowerCase().endsWith(EbookConstants.EBOOKEXT))
        	{
    			String refile = filepath.substring(0, filepath.lastIndexOf('.') + 1);
            	refile += EbookConstants.EBOOKEXT;
            	File file = new File(refile);
            	if(file.exists())
            	{
            		if(InitPlayFile(refile,m_Pdfsize,0) == -1)
            			return -1;    	
            	}
            	else
            	{
            		return -1;
            	}
        	}
    		return seekPlayPos(seekpos,len);
    	}
    }
    public int InitPlayFile(String file,long StartAddr,long len)
    {
    	int ret = 0;
    	
    	m_currentfilesize = 0;
    	ret = initAudioPlayer(file,StartAddr,len);
    	if(ret > 0)
    	{
    		filepath = file;
    		if(file.toLowerCase().endsWith(EbookConstants.EBOOKEXT))
    		{
    			m_FileSwapOffset = ret;// - 268;
    		}
    		m_currentfilesize = ret;
    	}
    	return ret;
    }
}  